<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useCommentAPI } from "@/services/comment";
import { useUserStore } from "@/stores/user";
import { IconReply } from "@/components/icons";
const userStore = useUserStore();

const props = defineProps<{
  comments: any[];
  musicId?: string;
  playlistId?: string;
  singerId?: string; // 添加歌手ID属性
}>();

const emit = defineEmits<{
  (e: "commentAdded"): void;
}>();

const commentAPI = useCommentAPI();
const newComment = ref("");
const submitting = ref(false);
const replyingTo = ref<string | null>(null);
const replyContent = ref("");
const replySubmitting = ref(false);

const MAX_COMMENT_LENGTH = 140;
const remainingChars = computed(
  () => MAX_COMMENT_LENGTH - newComment.value.length
);

// 添加二级回复字数限制
const replyRemainingChars = computed(
  () => MAX_COMMENT_LENGTH - replyContent.value.length
);

const createTempComment = () => {
  const tempComment = {
    fatherComment: {
      avatarUrl: userStore.avatarUrl,
      uname: userStore.username,
      comment: {
        commentId: `temp-${Date.now()}`, // 临时ID
        commentContent: newComment.value,
        commentDate: new Date().toISOString(),
      },
    },
    sonCommentList: [],
  };
  return tempComment;
};

const handleSubmitComment = async () => {
  if (
    !newComment.value.trim() ||
    submitting.value ||
    newComment.value.length > MAX_COMMENT_LENGTH
  )
    return;

  const tempComment = createTempComment();
  props.comments.unshift(tempComment); // 先添加临时评论

  try {
    submitting.value = true;
    const commentData = {
      lid: userStore.uid, // 当前用户ID
      commentContent: newComment.value.trim(),
      musicId: props.musicId || "", //若给音乐发送评论，否则为空字符串
      playlistId: props.playlistId || "", // 添加歌单ID
      singerId: props.singerId || "", // 添加歌手ID
    };

    await commentAPI.addComment(commentData);
    newComment.value = "";
    emit("commentAdded");
  } catch (error) {
    console.error("发布评论失败:", error);
    // 发送失败时移除临时评论
    const tempIndex = props.comments.findIndex(
      (c) =>
        c.fatherComment.comment.commentId ===
        tempComment.fatherComment.comment.commentId
    );
    if (tempIndex > -1) {
      props.comments.splice(tempIndex, 1);
    }
  } finally {
    submitting.value = false;
  }
};

const createTempReply = (parentCommentId: string) => {
  return {
    avatarUrl: userStore.avatarUrl,
    uname: userStore.username,
    comment: {
      commentId: `temp-reply-${Date.now()}`,
      commentContent: replyContent.value,
      commentDate: new Date().toISOString(),
    },
  };
};

const handleReplySubmit = async (parentCommentId: string) => {
  if (
    !replyContent.value.trim() ||
    replySubmitting.value ||
    replyContent.value.length > MAX_COMMENT_LENGTH
  )
    return;

  const parentComment = props.comments.find(
    (c) => c.fatherComment.comment.commentId === parentCommentId
  );
  if (!parentComment) return;

  // 创建并添加临时回复
  const tempReply = createTempReply(parentCommentId);
  parentComment.sonCommentList.push(tempReply);

  try {
    replySubmitting.value = true;
    const replyData = {
      pid: parentCommentId,
      commentContent: replyContent.value.trim(),
      replyId: userStore.uid,
      responfentId: parentComment.fatherComment.lid,
    };

    await commentAPI.addComment(replyData);
    replyContent.value = "";
    replyingTo.value = null;
    emit("commentAdded");
  } catch (error) {
    console.error("发送回复失败:", error);
    // 发送失败时移除临时回复
    const replyIndex = parentComment.sonCommentList.findIndex(
      (reply: any) => reply.comment.commentId === tempReply.comment.commentId
    );
    if (replyIndex > -1) {
      parentComment.sonCommentList.splice(replyIndex, 1);
    }
  } finally {
    replySubmitting.value = false;
  }
};

const sortedComments = computed(() => {
  return [...props.comments].sort((a, b) => {
    return (
      new Date(b.fatherComment.comment.commentDate).getTime() -
      new Date(a.fatherComment.comment.commentDate).getTime()
    );
  });
});

onMounted(() => {
  // 初始化评论数据
  console.log(props.comments);
});
</script>

<template>
  <div class="comment-section">
    <h2 class="text-xl font-bold mb-6">评论区</h2>
    <!-- 评论输入框 -->
    <div class="bg-gray-50 rounded-lg mb-6">
      <div class="flex gap-4 items-start">
        <img
          :src="userStore.avatarUrl"
          alt="用户头像"
          class="w-10 h-10 rounded-full bg-gray-200 object-cover flex-shrink-0"
        />
        <div class="flex-1 min-w-0">
          <el-input
            v-model="newComment"
            type="textarea"
            :rows="3"
            :maxlength="MAX_COMMENT_LENGTH"
            placeholder="说点什么吧..."
            class="mb-2 w-full"
            resize="none"
            :show-word-limit="false"
          />
          <div class="flex justify-between items-center">
            <span
              class="text-sm"
              :class="{
                'text-red-500': remainingChars < 0,
                'text-gray-400': remainingChars >= 0,
              }"
            >
              还可以输入{{ remainingChars }}字
            </span>
            <el-button
              type="primary"
              :loading="submitting"
              :disabled="!newComment.trim() || submitting || remainingChars < 0"
              @click="handleSubmitComment"
            >
              发布评论
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="divide-y divide-gray-200">
      <div v-if="comments.length === 0" class="py-6 text-center text-gray-500">
        暂无评论，快来发表第一条评论吧！
      </div>
      <div
        v-else
        v-for="comment in sortedComments"
        :key="comment.fatherComment.comment.commentId"
        class="py-4 first:pt-0 border-t border-gray-200 first:border-t-0"
      >
        <!-- 父评论 -->
        <div class="flex gap-4 items-start">
          <img
            :src="comment.fatherComment.avatarUrl"
            alt="用户头像"
            class="w-10 h-10 rounded-full bg-gray-200 object-cover flex-shrink-0"
          />
          <div class="flex-1 min-w-0">
            <div class="flex items-center gap-2 flex-wrap">
              <span class="font-medium hover:text-[#ec4141] cursor-pointer">
                {{ comment.fatherComment.uname }}
              </span>
              <span class="text-gray-400 text-xs">{{
                new Date(
                  comment.fatherComment.comment.commentDate
                ).toLocaleString()
              }}</span>
            </div>
            <p class="mt-2 text-gray-700 leading-relaxed break-words">
              {{ comment.fatherComment.comment.commentContent }}
            </p>

            <div class="mt-2 flex items-center gap-4">
              <button
                text
                class="flex items-center gap-1 text-gray-500 hover:text-black hover:font-semibold text-xs"
                @click="replyingTo = comment.fatherComment.comment.commentId"
              >
                <IconReply class="w-8 h-8" />
                回复
              </button>
            </div>

            <!-- 回复输入框 -->
            <div
              v-if="replyingTo === comment.fatherComment.comment.commentId"
              class="mt-4"
            >
              <el-input
                v-model="replyContent"
                type="textarea"
                :rows="3"
                :maxlength="MAX_COMMENT_LENGTH"
                placeholder="回复评论..."
                class="mb-2 w-full"
                resize="none"
                :show-word-limit="false"
              />
              <div class="flex justify-between items-center">
                <span
                  class="text-sm"
                  :class="{
                    'text-red-500': replyRemainingChars < 0,
                    'text-gray-400': replyRemainingChars >= 0,
                  }"
                >
                  还可以输入{{ replyRemainingChars }}字
                </span>
                <div class="flex gap-2">
                  <el-button @click="replyingTo = null">取消</el-button>
                  <el-button
                    type="primary"
                    :loading="replySubmitting"
                    :disabled="
                      !replyContent.trim() ||
                      replySubmitting ||
                      replyRemainingChars < 0
                    "
                    @click="
                      handleReplySubmit(comment.fatherComment.comment.commentId)
                    "
                  >
                    回复
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 子评论列表 -->
        <div v-if="comment.sonCommentList.length > 0" class="ml-14 mt-6">
          <div
            v-for="reply in comment.sonCommentList"
            :key="reply.comment.commentId"
            class="flex gap-4 items-start mb-4 last:mb-0"
          >
            <img
              :src="reply.avatarUrl"
              alt="用户头像"
              class="w-8 h-8 rounded-full bg-gray-200 object-cover flex-shrink-0"
            />
            <div class="flex-1 min-w-0">
              <div class="flex items-center gap-2 flex-wrap">
                <span class="font-medium hover:text-[#ec4141] cursor-pointer">
                  {{ reply.uname }}
                </span>
                <span class="text-gray-400 text-xs">{{
                  new Date(reply.comment.commentDate).toLocaleString()
                }}</span>
              </div>
              <p class="mt-2 text-gray-700 leading-relaxed break-words">
                {{ reply.comment.commentContent }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.comment-section {
  max-width: 100%;
  margin: 0 auto;
}

/* 添加悬停效果使分割线更明显 */
.comment-section > div > div:hover {
  background-color: rgba(0, 0, 0, 0.01);
}
</style>
